package com.hgsoft.yfzx.component.runninglog.component.log;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * description
 *
 * @author sawyerlsy
 * @date 2018-12-28
 * @since
 */
public class LoggerQueue {
    /**
     * 队列大小,限制阻塞队列最大容量,防止将内存塞爆
     */
    private static final int QUEUE_MAX_SIZE = 10000;

    /**
     * 定义一个阻塞队列存放消息
     */
    private BlockingQueue<LogMessage> blockingQueue = new LinkedBlockingQueue<>(QUEUE_MAX_SIZE);

    private static class LoggerQueueSingleton {
        private static LoggerQueue loggerQueue = new LoggerQueue();
    }


    private LoggerQueue() {
    }

    public static LoggerQueue getInstance() {
        return LoggerQueueSingleton.loggerQueue;
    }

    /**
     * 消息入队,调用add方法,队列满了就抛出异常
     * <p>
     * 该方法只在WebSocketAppender中调用,而日志的输入可能非常频繁,为了避免占用过多的线程资源，这里使用不阻塞的方法
     * </p>
     *
     * @param logMessage 消息对象
     */
    public boolean push(LogMessage logMessage) {
        return this.blockingQueue.add(logMessage);
    }

    /**
     * 消息出队,调用take方法阻塞线程,直到拿到消息为止
     */
    public LogMessage poll() {
        LogMessage result = null;
        try {
            result = this.blockingQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return result;
    }
}
